package com.gx.security.digital_signature;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.security.*;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by gx on 2017/3/30.
 */
public class ECDSATest {
    private static final String src = "imooc security signatureECDSA";

    public static void main(String[] args) {
        jdkECDSA();
    }

    public static void  jdkECDSA(){
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");

            //初始化长度
            keyPairGenerator.initialize(256);
//            keyPairGenerator.initialize(1024, new SecureRandom());
            //获得 key对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //公钥进行验证
            ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
            //私钥进行签名
            ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();
            System.out.println("Public Key:" + Base64.encodeBase64String(ecPublicKey.getEncoded()));
            System.out.println("PrivateKey :" + Base64.encodeBase64String(ecPrivateKey.getEncoded()));


            //执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1withECDSA");
            signature.initSign(privateKey);
            //输入执行加密的内容
            signature.update(src.getBytes());
            //获得签名
            byte [] result  = signature.sign();
            System.out.println("JDK ECDSA sign 实现"+ Hex.encodeHexString(result));


            //验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("EC");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            //得到签名
            signature = Signature.getInstance("SHA1withECDSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            boolean bool = signature.verify(result);
            System.out.println("RSA 验证结果——-->"+bool);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
